<template>
  <div>
    <a-card :title="`${+type===1?'':action===1?'权属户新增':action===2?'权属户详情':'权属户查看'}`" :bordered="false">
      <a-card title="户基本信息" :bordered="false">
        <a-form
          ref="formInfoRef"
          id="formInfoRef"
          :form="formInfo"
          layout="inline"
          :class="{ disable: action === 3 }">
          <a-row :gutter="48">
            <a-col :md="7" :sm="24" style="height:60px">
              <a-form-item :label="$t('house.houseNo')">
                <a-input
                  style="width: 140px"
                  name="houseNo"
                  v-decorator="[
                    'houseNo',
                    {rules: [{ required: true, message: '户编号不能为空!'},
                             { min: 3, message: '户编号至少3位!' }]
                     ,validateTrigger:['blur','change']}

                  ]"
                  :placeholder="$t('house.houseNo.placeholder')" />
              </a-form-item>
            </a-col>
            <a-col :md="7" :sm="24" style="height:60px">
              <a-form-item :label="$t('house.householderName')">
                <a-input
                  style="width: 140px"
                  name="householderName"
                  v-decorator="[
                    'householderName',
                    {rules: [{ required: true, message: '户主姓名不能为空!'}]
                     ,validateTrigger:['blur']}

                  ]"
                  :placeholder="$t('house.householderName.placeholder')"
                  @change="inputChange"
                />
              </a-form-item>
            </a-col>
            <a-col :md="10" :sm="24" style="height:60px">
              <a-form-item :label="$t('house.houseAddress')">
                <a-input
                  style="width: 230px"
                  name="houseAddress"
                  v-decorator="['houseAddress',{rules: [{ required: true, message: '户所在地不能为空!'}]}]"
                  :placeholder="$t('house.houseAddress.placeholder')"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="户实物指标信息" :bordered="false">
        <a-tabs v-model:activeKey="activeKey" tab-position="left" animated>
          <a-tab-pane key="1" :tab="`家庭成员信息 (${familyMemberList.length})`">
            <a-button
              v-if="action !== 3"
              class="editable-add-btn"
              style="margin-bottom: 8px;float:right;z-index:99"
              type="primary"
              @click="newMember">{{ $t('common.add') }}</a-button>
            <a-table :class="{ disable: action === 3 }" :columns="familyMemberColumns" :pagination="false" :dataSource="familyMemberList" :loading="memberLoading">
              <template slot="key" slot-scope="text, record">
                {{ record.key }}
              </template>
              <template slot="memberRelation" slot-scope="text, record">
                <a-modal
                  v-model:open="openModel"
                  title="确认"
                  :keyboard="true"
                  @ok="handleOk"
                  @cancel="handleCancel"
                >
                  <p>只能有一个人为户主,是否确认更新?</p>
                </a-modal>
                <a-select
                  key="memberRelation"
                  :value="text?text:undefined"
                  style="width:180px"
                  placeholder="请选择与户主的关系"
                  @change="(e) => handleChange(e, record.key, 'memberRelation','familyMemberList')"
                >
                  <!-- <a-select-option value="" ><span style="color:#bdc3c7">请选择与户主的关系</span></a-select-option> -->
                  <a-select-option value="户主">户主</a-select-option>
                  <a-select-option value="配偶">配偶</a-select-option>
                  <a-select-option value="子女">子女</a-select-option>
                </a-select>
              </template>
              <template v-for="(col, i) in ['name','idCard','birthday']" :slot="col" slot-scope="text, record,index">
                <a-input
                  :key="col"
                  style="margin: -5px 0"
                  :value="text"
                  :placeholder="placeholderTips[i]"
                  @change="(e) => handleChange(e.target.value, record.key, col,'familyMemberList')"
                />
              </template>

              <template slot="operation" slot-scope="text, record">
                <span>
                  <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key,'familyMemberList')">
                    <a class="operation">{{ $t('common.delete') }}</a>
                  </a-popconfirm>
                </span>
              </template>
            </a-table>

          </a-tab-pane>
          <a-tab-pane key="2" :tab="`房屋信息 (${houseInfoList.length})`">
            <a-button
              v-if="action !== 3"
              class="editable-add-btn"
              style="margin-bottom: 8px;float:right;z-index:99"
              type="primary"
              @click="newHouseInfo">{{ $t('common.add') }}</a-button>
            <a-table :class="{ disable: action === 3 }" :columns="houseInfoColumns" :pagination="false" :dataSource="houseInfoList" :loading="memberLoading">
              <template slot="key" slot-scope="text, record">
                {{ record.key }}
              </template>
              <template slot="owner" slot-scope="text, record">
                <a-select
                  key="owner"
                  :value="text?text:undefined"
                  style="width:180px"
                  placeholder="请选择权属人"
                  :options="ownerSelect"
                  @change="(e) => handleChange(e, record.key, 'owner','houseInfoList')"
                >

                </a-select>
              </template>
              <template slot="region" slot-scope="text, record">
                <a-input
                  key="region"
                  style="margin: -5px 0"
                  :value="text"
                  placeholder="请输入房屋所在行政区划"
                  @change="(e) => handleChange(e.target.value, record.key, 'region','houseInfoList')"
                />
              </template>
              <template slot="houseArea" slot-scope="text, record">
                <a-input
                  key="houseArea"
                  style="margin: -5px 0"
                  :value="text"
                  placeholder="请输入房屋面积"
                  @change="(e) => handleChange(e.target.value, record.key, 'houseArea','houseInfoList')"
                />
              </template>

              <template slot="operation" slot-scope="text, record">
                <span>
                  <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key,'houseInfoList')">
                    <a class="operation">{{ $t('common.delete') }}</a>
                  </a-popconfirm>
                </span>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>
      <a-divider />
      <a-row v-if="action!==3">
        <a-col :span="4" :offset="10">
          <a-space align="center" size="large">
            <a-button type="primary" @click="save" :loading="saveBtn" >保存</a-button>
            <a-button v-if="type===1" @click="shadown">关闭</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import { ref } from 'vue'
import { addFamilyInfoApi, detailApi } from '@/api/house'

const activeKey = ref('1')
// 表单字段

const fields = ['houseNo', 'householderName', 'houseAddress']
export default {
  name: 'HouseDetail',
  components: {
    STable
  },
  props: {
    type: {
      type: Number,
      default: 0
    },
     // 当前动作,1为新增,2为详情,3为查看
    action: {
      type: Number,
      default: 1
    },
    currentId: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      saveBtn: false,
      openModel: false,
      modelKey: 0,
      checkField: ['name', 'memberRelation', 'idCard', 'birthday', 'owner', 'region', 'houseArea'],
      fieldMapper: {
        memberRelation: '请选择与户主关系',
        name: '请填写姓名',
        idCard: '请填写身份证号',
        birthday: '请填写出生日期',
        owner: '请选择权属人',
        region: '请输入房屋所在行政区划',
        houseArea: '请输入房屋面积'
      },
      memberLoading: false,
      // 表单信息
      formInfo: {
        id: '',
        householderName: '',
        houseNo: '',
        houseAddress: ''
      },
      // 当前激活tab
      activeKey,
      placeholderTips: ['请输入姓名', '请输入身份证号', '出生日期'],
      familyMemberColumns: [
        {
          title: '序号',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'key' }
        },
        {
          title: '姓名',
          dataIndex: 'name',
          align: 'center',
          width: '14%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '与户主关系',
          dataIndex: 'memberRelation',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'memberRelation' }
        },
         {
          title: '身份证号',
          dataIndex: 'idCard',
          align: 'center',
          width: '24%',
          scopedSlots: { customRender: 'idCard' }
        },
         {
          title: '出生日期',
          dataIndex: 'birthday',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'birthday' }
        },
         {
          title: '操作',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }

      ],
      familyMemberList: [
        // {
        //   key: '1',
        //   name: '张三',
        //   memberRelation: '户主',
        //   idCard: '410323200002205055',
        //   birthday: '2000-02-20'
        // }
      ],
      houseInfoColumns: [
        {
          title: '序号',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'key' }
        },
        {
          title: '权属人',
          dataIndex: 'owner',
          align: 'center',
          width: '25%',
          scopedSlots: { customRender: 'owner' }
        },
        {
          title: '所在行政区划',
          dataIndex: 'region',
          align: 'center',
          width: '30%',
          scopedSlots: { customRender: 'region' }
        },
         {
          title: '房屋面积',
          dataIndex: 'houseArea',
          align: 'center',
          width: '25%',
          scopedSlots: { customRender: 'houseArea' }
        },
         {
          title: '操作',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }

      ],
      houseInfoList: [
        // {
        //   key: '1',
        //   owner: '',
        //   region: '',
        //   houseArea: ''
        // }
      ],
      ownerSelect: []

    }
  },
  computed: {
    title () {
      return this.$route.meta.title
    }
  },
  created () {
    this.formInfo = this.$form.createForm(this)
    // fields.forEach(v => this.form.getFieldDecorator(v))
    if (this.action === 1) {
      this.ownerSelect = []
    }
  },
  async mounted () {
    const id = this.currentId
    const action = this.action
    console.log(this.currentId, '   ', this.action, 'mounted')
    if (id > 0 && (action === 2 || action === 3)) {
      const res = await detailApi(this.currentId)
      const { data } = res
      console.log(data)
      this.formInfo.setFieldsValue({ ...data.familyInfo })
      this.familyMemberList = data.familyMemberList
      // this.listSort('familyMemberList')
      this.houseInfoList = data.houseInfoList
      this.listSort('houseInfoList')
      this.ownerSelect = this.familyMemberList.map(item => {
        return { label: item.name, value: item.key }
      })
    }
  },
  methods: {
    // 新增家庭成员,校验当前最后一行的值
    newMember () {
      // 校验
      if (!this.checkMember()) return
      // 校验通过,向数组push一个空元素
      this.familyMemberList.push({
        key: '',
        name: '',
        idCard: '',
        birthday: ''
      })
      // 对key重排序
      this.listSort('familyMemberList')
    },
    checkMember () {
      const length = this.familyMemberList.length
      for (let i = 0; i < length; i++) {
        const current = this.familyMemberList[i]
        // 遍历校验
        for (var field in current) {
          // 空校验
          if (this.checkField.includes(field) && !current[field]) {
            this.$message.error(`家庭成员信息第${current['key']}行：${this.fieldMapper[field]}`)
            return false
          }
          // 身份证格式校验
          if (field === 'idCard') {
            // 支持一代身份证和二代身份证校验
          const regExp = /(^\d{15}$)|(^\d{17}(\d|Xx)$)/
          if (!regExp.test(current[field])) {
              this.$message.error(`家庭成员信息第${current['key']}行：身份证格式不正确`)
              return false
          }
          }
          if (field === 'birthday') {
              // 生日格式校验
              const birthRegExp = /^\d{4}-\d{2}-\d{2}$/
              if (!birthRegExp.test(current[field])) {
                  this.$message.error(`家庭成员信息第${current['key']}行：出生年月格式：yyyy-MM-dd`)
                  return false
              }
              // 生日与身份证是否对应
              if (!current['idCard'].includes(current['birthday'].replaceAll(/-/g, ''))) {
                    this.$message.error(`家庭成员信息第${current['key']}行：出生年月与身份证信息不一致`)
                    return false
              }
          }
        }
      }
      return true
    },
    // 新增房屋信息,校验当前最后一行的值
    newHouseInfo () {
      // 校验
      if (!this.checkHouse()) return
      // 添加新元素
      this.houseInfoList.push({
        key: '',
        owner: '',
        region: '',
        houseArea: ''
      })
      // 对key重排序
      this.listSort('houseInfoList')
    },
    // 检查房屋信息
    checkHouse () {
      const length = this.houseInfoList.length
      // 从第一行开始校验
      for (let i = 0; i < length; i++) {
        const current = this.houseInfoList[i]
        // 校验每个字段
        for (var field in current) {
          console.log(field, current[field], 'field校验')
          // 空校验
          if (this.checkField.includes(field) && !current[field]) {
            this.$message.error(`房屋信息第${current['key']}行：${this.fieldMapper[field]}`)
            return false
          }
          // 房屋面积校验
          if (field === 'houseArea') {
            console.log(field, current[field], 'field校验')
            const regExp = /^-?\d*\.?\d+$/
            console.log(!regExp.test(+current[field]), '!regExp.test(+current[field])')
            if (!regExp.test(+current[field])) {
              this.$message.error(`房屋信息第${current['key']}行：房屋面积应为纯数字`)
              return false
            }
            if (+current[field] <= 0) {
              this.$message.error(`房屋信息第${current['key']}行：房屋面积应大于0`)
              return false
            }
          }
      }
      }
      return true
    },
    // 集合key重新排序,从1到n
    listSort (listName) {
      // 将key重新排序
      this[listName] = this[listName].map((item, index) => {
        item['key'] = index + 1
        return item
      })
    },
    // 检测表单改变事件
    handleChange (value, key, column, listName) {
      console.log(value, key, column, listName, '改变事件')
      const newData = [...this[listName]]
      const target = newData.find(item => key === item.key)
      // 只能有一个户主
      if (column === 'memberRelation' && value === '户主') {
        // 是否第二次选择户主
        let bool = false
        for (let i = 0; i < newData.length; i++) {
        if (newData[i][column] === '户主') {
              this.modelKey = key
              this.openModel = true
              bool = true
              // this.$message.error('只能有一个人为户主')
              // target[column] = ''
              // this[listName] = newData
              // return
            }
        }
       // 如果第二次不更新值
       if (!bool) {
        // 将户主姓名赋值给基础信息的户主名称
         this.$nextTick(() => {
          this.formInfo.setFieldsValue({ 'householderName': target['name'] })
          })
       }
      }
      // 如果更改的是姓名,且与户主关系为户主,更新新名称为户主名称
      if (column === 'name' && target['memberRelation'] === '户主') {
        this.$nextTick(() => {
         this.formInfo.setFieldsValue({ 'householderName': value })
        })
      }
      // 身份证校验,校验通过时,填充生日
      if (column === 'idCard') {
         const regExp = /(^\d{15}$)|(^\d{17}(\d|Xx)$)/
         if (regExp.test([value]) && target) {
         const regExp1 = /(^\d{6})(\d{8})(\d{3})([\dXx])$/
         const match = regExp1.exec(value)
         target['birthday'] = match[2].substring(0, 4) + '-' + match[2].substring(4, 6) + '-' + match[2].substring(6, 8)
         }
      }

      // 拷贝原数组
      // 找到更改的key
      if (target) {
        // 更新字段名为column的值
        target[column] = value
        // 重新赋值
        this[listName] = newData
      }
      if (column === 'name') {
        // 如果更改的是姓名,更新房源权属人下拉框
         this.ownerSelect = this[listName].map(item => {
          return { label: item.name, value: item.key }
         })
         // 同步更新下拉框的值
        const house = this.houseInfoList.find(item => item.owner === key)
        console.log(house, 'house===')
        house.owner = key
      }
      console.log(this[listName])
    },
    // 对话框确认事件
    handleOk () {
      const key = this.modelKey
      console.log(key, '确认===>')
      if (key) {
        // 如果key存在,找出关系为户主,且key不等于当前key的对象
        const target = this.familyMemberList.find(item => item.memberRelation === '户主' && +item.key !== +key)
        const source = this.familyMemberList.find(item => item.memberRelation === '户主' && +item.key === +key)
        // 将其关系置空
        target.memberRelation = ''
        console.log(target, 'target')
        // 更新户主名称为当前户主
        this.$nextTick(() => {
          this.formInfo.setFieldsValue({ 'householderName': source.name })
        })
        // 关闭对话框
        this.openModel = false
      }
    },
    // 对话框取消事件
    handleCancel () {
      const key = this.modelKey
      console.log(key, '取消===>')
      if (key) {
        // 如果key存在,找到当前取消的对象
        const target = this.familyMemberList.filter(item => +item.key === +key)
        // 将其关系置空
        target[0].memberRelation = ''
      }
    },
    // 移除指定数组的指定元素
    remove (key, listName) {
      // 如果删除的是家庭成员且有房屋指标,不进行
      console.log(key, listName, '===')
      if (listName === 'familyMemberList') {
        debugger
        const target = this[listName].filter(item => item.key === key)
        const obj = this.houseInfoList.filter(item => item.owner === target[0].name)
        if (target[0].name && obj.length > 0) {
          this.$message.error(`当前成员是房屋指标第${obj[0].key}行权属人,请先删除!`)
          return
        }
      }
      // 过滤数组,滤掉指定key的元素
      const newData = this[listName].filter(item => item.key !== key)
      this[listName] = newData
      // 如果数组为空或长度为0时添加一个新元素
      if (this[listName] && this[listName].length === 0) {
        if (listName === 'familyMemberList') {
          this.newMember()
        } else {
          this.newHouseInfo()
        }
      }
      this.listSort(listName)
    },
    // 保存数据
    save () {
      console.log('sss')
      this.saveBtn = true
      this.formInfo.validateFields(async (err, values) => {
      console.log(err, values)
        if (err) {
          const el = document.getElementById('formInfoRef')
          if (el) {
            // 使用window.scrollTo实现平滑滚动
            window.scrollTo({
              top: el.offsetTop,
              behavior: 'smooth'
            })
          }
          this.saveBtn = false
        } else {
          console.log(11)
          let bool = false
            if (this.checkMember()) bool = this.checkHouse()
            if (bool) {
               const formData = { ...this.formInfo.getFieldsValue(), familyMembers: this.familyMemberList, houseInfos: this.houseInfoList }
               if (this.currentId > 0 && this.action === 2) {
                formData.id = this.currentId
               }
               console.log(formData, '最终数据===>')
               await addFamilyInfoApi(formData)
               this.$message.success('保存成功')
               this.saveBtn = false
               if (+this.type === 0) {
                 this.$router.push({ path: '/house/list' })
               } else {
                 this.$emit('shadown')
               }
            }
        }
      })

      // 校验
    },
    inputChange (e) {
        // 更新户主名称
        const target = this.familyMemberList.find(item => item.memberRelation === '户主')
        if (target) {
          console.log(this.familyMemberList, 'familyMemberList')
          console.log(this.houseInfoList, 'houseInfoList')
          //  // 同步更新下拉框的值
          // const house = this.houseInfoList.find(item => item.owner === target['key'])
          // console.log(house, 'houseInfoList')
          target['name'] = e.target.value
          this.ownerSelect = this.familyMemberList.map(item => {
              return { label: item.name, value: item.key }
          })
          // house.owner = target['key']
        }
    },
    shadown () {
       this.$emit('shadown')
    }
  }
}
</script>
<style scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
/* antdv 4.0 之前不支持表单禁用,通过Css控制 */
.disable {
  pointer-events: none;
}
.disable input {
  cursor: not-allowed;
  background: #f5f5f5;
}
.disable .operation {
  color: #9aa7b1;
}
::v-deep .disable .ant-select-selection--single {
  background: #f5f5f5 !important;
}
::v-deep .ant-input-number-handler-wrap {
    display: none;
}
.boxStyle{
  width: 100%;
  height: 120px;
  borderRadius: 6px;
  border: 1px solid #40a9ff;
}
</style>
